﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

namespace MiscLib
{
    public class DynamicExpress
    {
        static string CreateCode(string para)
        {
            return "using System; namespace ANameSpace{static class AClass{public static object AFunc(){return " + para + ";}}}";
        }

        public static string GetValue(string Express)
        {
            object obj = new object();
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameter = new CompilerParameters();
            parameter.ReferencedAssemblies.Add("System.dll");
            parameter.GenerateExecutable = false;
            parameter.GenerateInMemory = true;

            CompilerResults result = provider.CompileAssemblyFromSource(parameter,
                CreateCode(Express));//将你的式子放在这里
            if (result.Errors.Count > 0)
            {
                Console.WriteLine("动态编译出错了！");
            }
            else
            {
                Assembly assembly = result.CompiledAssembly;
                Type AType = assembly.GetType("ANameSpace.AClass");
                MethodInfo method = AType.GetMethod("AFunc");
                obj =method.Invoke(null, null);
            }

            return obj.ToString();    
        }
    }
}
